import { login, logout, getInfo,user } from '@/api/user'
// import userApi from '@/api/user'

import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { stat } from 'fs'



const state = {
  token:localStorage.getItem('token_key') || '',
   userInfo:{}
}

const mutations = {
   SET_TOKEN:(state,token)=>{
      state.token = token
   },
   SET_USERINFO:(state,userInfo)=>{
     state.userInfo = userInfo
   },
   RESET_TOKEN:(state)=>{
    state.token = ''
    state.userInfo ={}
   }
}

const actions = {
  // 登录
  async login({commit},userInfo){
    try {
      let result = await login(userInfo)
      // console.log(result.token,'token')
      localStorage.setItem('token_key',result.token)
      commit('SET_TOKEN',result.token)
      // this.$router.push('/')
      console.log(111)
      return 'ok'
    } catch (error) {
      console.log(error)
      return Promise.reject(error)
    }
  },
  // 获取用户信息
  async getInfo({commit}){
    try {
       let result = await getInfo()
       let {name,avatar} = result
      //  console.log(result)
       commit('SET_USERINFO',{name,avatar})
    } catch (error) {
      console.log(error)
      return Promise.reject(error)
    }
  },
  
  // 退出登录的时候-重置token
  resetToken({commit}){
    // 清除token
     commit('RESET_TOKEN')
    // 清除localstorage的token
    localStorage.removeItem('token_key')
    // 清空用户信息
  },

  // 退出登录
  async logout({commit,dispatch}){
    try {
      await logout()
      dispatch('resetToken')
      return 'ok'
    } catch (error) {
       return Promise.reject(error)
    }
  }
   

  // // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // remove token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     removeToken() // must remove  token  first
  //     commit('RESET_STATE')
  //     resolve()
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

